<template>
  <div id="manageQuestionView">
    <!--搜索题目-->
    <a-form :model="searchParams" layout="inline" class="searchQuestionForm">
      <a-form-item field="id" label="题号" tooltip="精确匹配">
        <a-input
          v-model="searchParams.id"
          placeholder="请输入题号"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="title" label="题目" tooltip="模糊匹配">
        <a-input
          v-model="searchParams.title"
          placeholder="请输入题目"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        field="tags"
        label="标签"
        tooltip="输入标签后需要回车确认选中"
      >
        <a-input-tag
          v-model="searchParams.tags"
          placeholder="请输入标签"
          allow-clear
          style="min-width: 220px"
        />
      </a-form-item>
      <a-form-item field="userId" label="创建者" tooltip="精确匹配">
        <a-input
          v-model="searchParams.userId"
          placeholder="请输入用户Id"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button
          type="outline"
          shape="round"
          status="normal"
          @click="doSearch"
        >
          搜索
        </a-button>
      </a-form-item>
    </a-form>
    <!--题目表格-->
    <a-table
      :columns="columns"
      :data="data"
      :pagination="pagination"
      @page-change="onPageChange"
      column-resizable
      filter-icon-align-left
    >
      <template #tags="{ record }">
        <span v-for="(tag, index) in record.tags" :key="index">
          <a-tag v-if="tag === '简单'" class="tagsList" color="#00b42a">
            {{ tag }}
          </a-tag>
          <a-tag v-else-if="tag === '中等'" class="tagsList" color="#ffb400">
            {{ tag }}
          </a-tag>
          <a-tag v-else-if="tag === '困难'" class="tagsList" color="#f53f3f">
            {{ tag }}
          </a-tag>
          <a-tag v-else class="tagsList" color="#86909c">{{ tag }}</a-tag>
        </span>
      </template>
      <template #createTime="{ record }">
        {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #updateTime="{ record }">
        {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #passingRate="{ record }">
        <strong>
          {{
            `${
              record.submitNum == 0
                ? "0"
                : Math.round((record.acceptedNum / record.submitNum) * 100)
            }%`
          }}
        </strong>
        {{ `(${record.acceptedNum + "/" + record.submitNum})` }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button
            type="primary"
            status="success"
            shape="round"
            @click="doEditQuestion(record.id)"
          >
            编辑
          </a-button>
          <a-popconfirm
            content="确定要干掉我?"
            position="bottom"
            type="error"
            @ok="doDeleteQuestion(record.id)"
          >
            <a-button type="primary" status="danger" shape="round">
              删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRaw, watchEffect } from "vue";
import { QuestionControllerService } from "../../../generated";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { useRouter } from "vue-router";

const router = useRouter();

// 表格列
const columns = [
  {
    dataIndex: "id",
    title: "题号",
    // width: 100,
    align: "center",
    ellipsis: true,
    tooltip: true,
  },
  {
    dataIndex: "user.id",
    title: "创建者",
    // width: 80,
    align: "center",
    ellipsis: true,
    tooltip: true,
  },
  {
    dataIndex: "title",
    title: "题目",
    align: "center",
    ellipsis: true,
  },
  {
    title: "标签",
    width: 200,
    align: "center",
    slotName: "tags",
    filterable: {
      filters: [
        {
          text: "简单",
          value: "简单",
        },
        {
          text: "中等",
          value: "中等",
        },
        {
          text: "困难",
          value: "困难",
        },
      ],
      filter: (value: string, record: any) =>
        toRaw(record.tags).some((tag: string) => value.includes(tag)),
      multiple: true,
    },
  },
  {
    title: "通过数 / 提交数",
    width: 160,
    align: "center",
    ellipsis: true,
    tooltip: true,
    slotName: "passingRate",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "创建时间",
    width: 125,
    align: "center",
    ellipsis: true,
    tooltip: true,
    slotName: "createTime",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "更新时间",
    width: 125,
    align: "center",
    ellipsis: true,
    tooltip: true,
    slotName: "updateTime",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
  {
    title: "操作",
    align: "center",
    ellipsis: true,
    tooltip: true,
    slotName: "optional",
  },
];
// 数据列表
const data = ref([]);

// 搜索表单
const searchParams = ref({
  current: 1,
  pageSize: 10,
  id: null,
  title: "",
  tags: null,
  userId: null,
  sortField: "updateTime",
  sortOrder: "descend",
});

// 分页结果参数
let pagination = reactive({
  showTotal: true,
  current: 0,
  pageSize: 0,
  total: 0,
});

// 加载数据
const loadData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
    searchParams.value as any
  );
  if (res.code === 0) {
    // 数据赋值
    data.value = res.data.records;
    // 分页结果参数赋值
    pagination.total = Number(res.data.total);
    pagination.current = Number(res.data.current);
    pagination.pageSize = Number(res.data.size);
  } else {
    Message.error("获取数据失败，" + res.message);
  }
};

/**
 * 搜索
 */
const doSearch = () => {
  // 这里需要重置页号，不然你在第二页搜索第一页的内容，会搜不到
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

/**
 * 监听 () => { } 中的内容，
 * 内容中的变量（例如searchParams）发生改变时会再次触发() => { }中的内容（即loadData()重新加载数据）
 */
watchEffect(() => {
  loadData();
});

/**
 * 页码改变时触发
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 编辑题目
 * @param id 当前记录id
 */
const doEditQuestion = (id: number) => {
  router.push({
    path: "/question/update",
    query: {
      id,
    },
  });
};

/**
 * 删除题目
 * @param id 当前记录id
 */
const doDeleteQuestion = async (id: any) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: id,
  });
  if (res.code === 0) {
    Message.success("删除成功（蒜你狠！）");
    await loadData();
  } else {
    Message.error("哦吼，因为 " + res.message + " ，所以删除失败咯");
  }
};
</script>

<style scoped>
/*标签列表*/
.tagsList {
  margin: 3px;
}

/*搜索题目表单*/
.searchQuestionForm {
  justify-content: center;
  align-content: center;
  margin-bottom: 20px;
}
</style>